//
//  FriendInfoViewController.m
//  HotWord
//
//  Created by Ji Qi on 12-7-9.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "FriendInfoViewController.h"
#import "ConversationViewController.h"
#import "ServiceHelper.h"
#import "UserManager.h"

@interface FriendInfoViewController ()

@end

@implementation FriendInfoViewController
@synthesize friendsInfoTableView;
@synthesize backBtn;
@synthesize talkBtn;
@synthesize genderView;
@synthesize genderImageView;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithUser:(User *)user
{
    self = [super init];
    if (self) {
        _user = [user retain];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.friendsInfoTableView.top = self.view.height;
    self.backBtn.alpha = 0;
    self.talkBtn.alpha = 0;
    self.friendsInfoTableView.tableHeaderView = self.genderView;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    User *cacheUser = [[UserManager sharedManager] getCacheUser:_user.userId];
    if (!cacheUser) {
        [[HTActivityIndicator currentIndicator] displayActivity:@"Getting Profile..."];
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:_user.userId forKey:@"id"];
        [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeGetUserInfo WithParameters:params AndCallBackScope:self AndSuccessSel:@"getUserInfoSuccess:" AndFailedSel:@"getUserInfoFailed:"];
        [UIView animateWithDuration:0.5 
                         animations:^{
                             self.backBtn.alpha = 1;
                             self.talkBtn.alpha = 1;
                         }];
    }
    else {
        if (_user) {
            [_user release];
            _user = nil;
        }
        _user = [cacheUser retain];
        
        if ([@"Boy" isEqualToString:_user.gender]) {
            self.genderImageView.image = [UIImage imageNamed:@"himinfo.png"];
        }
        else if ([@"Girl" isEqualToString:_user.gender]) {
            self.genderImageView.image = [UIImage imageNamed:@"herinfo.png"];
        }
        [UIView animateWithDuration:0.5 
                         animations:^{
                             self.backBtn.alpha = 1;
                             self.talkBtn.alpha = 1;
                             self.friendsInfoTableView.top = 0;
                         }];
        [self.friendsInfoTableView reloadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [[HTActivityIndicator currentIndicator] hide];
    [super viewWillDisappear:animated];
    [UIView animateWithDuration:0.3 
                     animations:^{
                         self.backBtn.alpha = 0;
                         self.talkBtn.alpha = 0;
                     }];
}

- (void)getUserInfoSuccess:(NSObject *)result
{
    NSDictionary *dic = (NSDictionary *)result;
    NSString *code = [dic objectForKey:@"code"];
    if ([@"0" isEqualToString:code]) {
        User *user = [[[User alloc] init] autorelease];
        user.userId = _user.userId;
        NSDictionary *dataDic = [dic objectForKey:@"data"];
        user.nickname = [UtilHelper getStringValue:[dataDic objectForKey:@"nick"]];
        user.gender = [UtilHelper getStringValue:[dataDic objectForKey:@"gender"]];
        if ([@"F" isEqualToString:user.gender]) {
            user.gender = @"Girl";
        }
        else if ([@"M" isEqualToString:user.gender]) {
            user.gender = @"Boy";
        }
        user.longitude = [UtilHelper getStringValue:[dataDic objectForKey:@"longitude"]];
        user.latitude = [UtilHelper getStringValue:[dataDic objectForKey:@"latitude"]];
        user.avater = [UtilHelper getStringValue:[dataDic objectForKey:@"avater"]];
        user.avater1 = [UtilHelper getStringValue:[dataDic objectForKey:@"avater1"]];
        user.avater2 = [UtilHelper getStringValue:[dataDic objectForKey:@"avater2"]];
        user.exam = [UtilHelper getStringValue:[dataDic objectForKey:@"exam"]];
        if ([@"0" isEqualToString:user.exam]) {
            user.exam = @"SAT";
        }
        else if ([@"1" isEqualToString:user.exam]) {
            user.exam = @"GRE";
        }
        else if ([@"2" isEqualToString:user.exam]) {
            user.exam = @"GMAT";
        }
        else
        {
            user.exam = @"";
        }
        user.lastLogin = [UtilHelper getStringValue:[dataDic objectForKey:@"lastLogin"]];
        user.lastMsg = [UtilHelper getStringValue:[dataDic objectForKey:@"lastMsg"]];
        user.year = [UtilHelper getStringValue:[dataDic objectForKey:@"year"]];
        user.country = [UtilHelper getStringValue:[dataDic objectForKey:@"country"]];
        user.city = [UtilHelper getStringValue:[dataDic objectForKey:@"city"]];
        user.status = [UtilHelper getStringValue:[dataDic objectForKey:@"status"]];
        
        if (_user) {
            [_user release];
            _user = nil;
        }
        _user = [user retain];
        
        if ([@"Boy" isEqualToString:_user.gender]) {
            self.genderImageView.image = [UIImage imageNamed:@"himinfo.png"];
        }
        else if ([@"Girl" isEqualToString:_user.gender]) {
            self.genderImageView.image = [UIImage imageNamed:@"herinfo.png"];
        }
        [[UserManager sharedManager].cacheUsers addObject:user];
        [UIView animateWithDuration:0.5 
                         animations:^{
                             self.friendsInfoTableView.top = 0;
                         }];
        [self.friendsInfoTableView reloadData];
        [[HTActivityIndicator currentIndicator] hide];
    }
    else {
        [[HTActivityIndicator currentIndicator] displayFailed:@"get user failed!"];
    }
    
}

- (void)getUserInfoFailed:(NSObject *)result
{
    [[HTActivityIndicator currentIndicator] displayFailed:@"get user failed!"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        static NSString *CellIdentifier = @"UserHeadInfoCell";
        
        UserHeadInfoCell *cell = (UserHeadInfoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"UserHeadInfoCell" owner:self options:nil] objectAtIndex:0];
        }
        cell.delegate = self;
        [cell setUser:_user];
        return cell;
    }
    else {
        static NSString *CellIdentifier = @"UserInfoCell";
        
        UserInfoCell *cell = (UserInfoCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"UserInfoCell" owner:self options:nil] objectAtIndex:0];
        }
        
        if (indexPath.row == 1) {
            [cell setInfoTitle:@"Gender" infoValue:_user.gender pickMode:YES];
        }else if (indexPath.row == 2){
            [cell setInfoTitle:@"Test" infoValue:_user.exam pickMode:YES];
        }else if (indexPath.row == 3){
            [cell setInfoTitle:@"Age" infoValue:_user.year pickMode:YES];
        }else if (indexPath.row == 4){
            [cell setInfoTitle:@"Country/City" infoValue:_user.country pickMode:YES];
        }else if (indexPath.row == 5){
            [cell setInfoTitle:@"School/Major" infoValue:_user.city pickMode:YES];
        }else if (indexPath.row == 6){
            [cell setInfoTitle:@"I Am Looking For..." infoValue:_user.dreamSchoolCN pickMode:YES];
        }else if (indexPath.row == 7){
            [cell setInfoTitle:@"What's up" infoValue:_user.status pickMode:YES];
        }
        [cell setIndexPath:indexPath];
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 0) {
        return 80;
    }
    else if (indexPath.row == 7) {
        return 120;
    }
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (!_user) {
        return 0;
    }
    return 8;
}


- (void)viewDidUnload
{
    [self setBackBtn:nil];
    [self setTalkBtn:nil];
    [self setGenderView:nil];
    [self setGenderImageView:nil];
    [self setEnlargeImageContainer:nil];
    [self setEnlargeImageView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)tapOnBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)tapOnTalkBtn:(id)sender {
    if ([_user.userId isEqualToString:[UserManager sharedManager].currentUser.userId]) {
        [[HTActivityIndicator currentIndicator] displayMessage:@"You can't speak to yourself"];
        return;
    }
    
    ConversationViewController *conversationViewController = [[[ConversationViewController alloc] initWithUser:_user] autorelease];
    [self.navigationController pushViewController:conversationViewController animated:YES];
}

- (void)UserHeadInfoCellHeadDidSelected:(UserHeadInfoCell *)cell selectIndex:(NSInteger)index
{
    UIImage *image = nil;
    switch (index) {
        case 0:
            image = cell.headImageView.image;
            break;
        case 1:
            image = cell.headImageView1.image;
            break;
        case 2:
            image = cell.headImageView2.image;
            break;
            
        default:
            break;
    }
    if (!image) {
        return;
    }
    
    self.enlargeImageView.image = image;
    CGFloat imageHeight = image.size.height/image.size.width * 320;
    self.enlargeImageView.frame = CGRectMake(0, (self.enlargeImageContainer.height - imageHeight) / 2, 320, imageHeight);
    [UIView animateWithDuration:0.3f
                     animations:^{
                         self.enlargeImageContainer.alpha = 1;
                     }
                     completion:^(BOOL finished){
                         UITapGestureRecognizer *tapGesture = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToDismissImage)] autorelease];
                         [self.enlargeImageContainer addGestureRecognizer:tapGesture];
                     }];
}

- (void)tapToDismissImage
{
    [UIView animateWithDuration:0.3f
                     animations:^{
                        self.enlargeImageContainer.alpha = 0;
                     }
                     completion:^(BOOL finished){
                         for (UITapGestureRecognizer *gesture in self.enlargeImageContainer.gestureRecognizers) {
                             [self.view removeGestureRecognizer:gesture];
                         }
                     }];
}

- (void)dealloc {
    [_user release];
    [backBtn release];
    [talkBtn release];
    [genderView release];
    [genderImageView release];
    [_enlargeImageContainer release];
    [_enlargeImageView release];
    [super dealloc];
}
@end
